#!/bin/bash

# 生成只包含本地IP地址的SSL证书
# 不包含域名，只包含IP地址

set -e

echo "=== 生成只包含本地IP的SSL证书 ==="

# 获取本机IP地址
LOCAL_IP=$(ifconfig | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}' | head -1)
echo "检测到本机IP: $LOCAL_IP"

# 创建证书目录
mkdir -p nginx/ssl

# 生成只包含IP地址的证书
echo "生成SSL证书（仅IP地址）..."
openssl req -x509 -newkey rsa:4096 -keyout nginx/ssl/smartinput.key -out nginx/ssl/smartinput.crt -days 365 -nodes \
    -subj "/C=CN/ST=Beijing/L=Beijing/O=SmartInput/OU=Development/CN=$LOCAL_IP" \
    -addext "subjectAltName=DNS:localhost,IP:127.0.0.1,IP:$LOCAL_IP"

if [ $? -eq 0 ]; then
    echo "✅ 证书生成成功"
else
    echo "❌ 证书生成失败"
    exit 1
fi

# 生成PKCS12格式证书
echo "生成PKCS12格式证书..."
openssl pkcs12 -export -out nginx/ssl/smartinput.p12 -inkey nginx/ssl/smartinput.key -in nginx/ssl/smartinput.crt -passout pass:smartinput

if [ $? -eq 0 ]; then
    echo "✅ PKCS12证书生成成功"
else
    echo "❌ PKCS12证书生成失败"
    exit 1
fi

# 显示证书信息
echo ""
echo "=== 证书信息 ==="
echo "证书文件:"
ls -la nginx/ssl/

echo ""
echo "证书详情:"
openssl x509 -in nginx/ssl/smartinput.crt -text -noout | grep -A 10 "Subject Alternative Name"

echo ""
echo "=== 证书生成完成 ==="
echo "证书文件位置: nginx/ssl/"
echo "1. smartinput.crt - PEM格式证书"
echo "2. smartinput.key - PEM格式私钥"
echo "3. smartinput.p12 - PKCS12格式证书"
echo ""
echo "下一步："
echo "1. 导入证书到系统: ./import-cert-to-chrome.sh"
echo "2. 重启Nginx服务"
echo "3. 重新加载Chrome扩展" 